package org.cms.call;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

/**
 * Created by elnoa on 28/10/14.
 */
public class GetNewTokenCall extends AbstractCall<HttpPost> {

    private String refreshToken;
    private final String CLIENT_ID;
    private final String CLIENT_SECRET;
    private static final String REFRESH_TOKEN = "refresh_token";
    private String newAccessToken;

    public GetNewTokenCall(HttpClient httpclient, String refreshToken, String CLIENT_ID, String CLIENT_SECRET) {
        super(httpclient, "NOTNEEDED");
        this.refreshToken = refreshToken;
        this.CLIENT_ID = CLIENT_ID;
        this.CLIENT_SECRET = CLIENT_SECRET;
    }


    /**
     * post call
     * @return
     */
    public GetNewTokenCall invoke() {

        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("client_id", CLIENT_ID));
        postParameters.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
        postParameters.add(new BasicNameValuePair("grant_type", REFRESH_TOKEN));
        postParameters.add(new BasicNameValuePair("refresh_token", refreshToken));

        //Post Request
        HttpPost authorizeRequest = new HttpPost("https://accounts.google.com/o/oauth2/token");
        try {
            authorizeRequest.setEntity(new UrlEncodedFormEntity(postParameters));
            setRequest(authorizeRequest);

            setResponse(getHttpclient().execute(authorizeRequest));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (getResponse().getStatusLine().getStatusCode() < 400) {
            String content = getResponseContentAsString();
            String newToken = null;
            try {
                newToken = new JSONObject(content).getString("access_token");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            this.newAccessToken = newToken;
        }
        return this;
    }

    public String getNewAccessToken() {
        return newAccessToken;
    }
}